package com.ruoyi.riskrule.config.step1;

import com.ruoyi.bizsys.domain.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.riskrule.config.common.DeviceFingerprintEnum;
import com.ruoyi.riskrule.config.common.RuleUtils;
import com.ruoyi.riskrule.constants.Constants;
import com.ruoyi.riskrule.domain.RuleInCustomerData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.regex.Pattern;

@Slf4j
public class OriginalParamsLoader {

    /**
     * 为ruleIn填充CustomerData数据
     *
     * @param ruleIn
     * @param ruleInCustomerData
     */
    public static void setRuleInByCustomerData(RuleIn ruleIn, RuleInCustomerData ruleInCustomerData) {
        ruleIn.setSalary(monthlyIncomeFormat(ruleInCustomerData.getMonthlyIncome()));
        ruleIn.setEducation(ruleInCustomerData.getDegree());
        ruleIn.setNumofchildren(null != ruleInCustomerData.getChildrenNumber() ? String.valueOf(ruleInCustomerData.getChildrenNumber()) : null);
        ruleIn.setReligion(ruleInCustomerData.getReligion());
        ruleIn.setFristlanguage(ruleInCustomerData.getNativeLanguage());
        ruleIn.setEmail(ruleInCustomerData.getEmail());
        ruleIn.setJobtitle(ruleInCustomerData.getJobTitle());
        ruleIn.setJobtitleother(ruleInCustomerData.getJobTitleOther());
        ruleIn.setIndustry(ruleInCustomerData.getIndustry());
        ruleIn.setMarriage(ruleInCustomerData.getMaritalStatus());
        try {
            ruleIn.setEntrytime(StringUtils.isNotEmpty(ruleInCustomerData.getResumptionDate()) ?
                    new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new SimpleDateFormat("dd-MM-yyyy").parse(ruleInCustomerData.getResumptionDate())) : Constants.DEFAULT_TIME);
        } catch (ParseException e) {
            log.error("反人类日期转化失败:{}", e.getMessage());
        }
        ruleIn.setCustrating(ruleInCustomerData.getCreditRating());
        ruleIn.setSalarydate(ruleInCustomerData.getSalaryDate());
        ruleIn.setWorkaddress(ruleInCustomerData.getWorkingAddress());
        ruleIn.setWorkaddressdetail(ruleInCustomerData.getStreet());
        ruleIn.setResidentialstatus(ruleInCustomerData.getStateOfResidence());
        ruleIn.setOccupation(ruleInCustomerData.getOccupation());
        ruleIn.setOccupationother(ruleInCustomerData.getOccupationOther());
        ruleIn.setContactmobile(ruleInCustomerData.getRelatePhone());
        ruleIn.setRelation(ruleInCustomerData.getRelation());
        ruleIn.setContactname(StringUtils.removeNonBmpUnicodes(ruleInCustomerData.getRelateName()));
        String relatePhone2 = StringUtils.isNotBlank(ruleInCustomerData.getReplenishRelatePhone()) ? ruleInCustomerData.getReplenishRelatePhone() : ruleInCustomerData.getRelatePhone2();
        String relateName2 = StringUtils.isNotBlank(ruleInCustomerData.getReplenishRelateName()) ? ruleInCustomerData.getReplenishRelateName() : ruleInCustomerData.getRelateName2();
        String relation2 = StringUtils.isNotBlank(ruleInCustomerData.getReplenishRelation()) ? ruleInCustomerData.getReplenishRelation() : ruleInCustomerData.getRelation2();
        ruleIn.setEmcontactname(relateName2);
        ruleIn.setEmcontactnum(relatePhone2);
        ruleIn.setEmrelation(relation2);
        ruleIn.setCreditmodellevel(ruleInCustomerData.getCreditModelLevel());
        log.info("补充信息字段日志4：{}", ruleIn.toString());
    }

    /**
     * 为ruleIn填充DeviceInfo数据
     *
     * @param ruleIn
     * @param appDeviceInfo
     */
    public static void setRuleInByDeviceInfo(RuleIn ruleIn, AppDeviceInfo appDeviceInfo) {
        ruleIn.setAppVersion(appDeviceInfo.getAppVersion());
        ruleIn.setDeviceCountry(RuleUtils.getRuleAppValue(appDeviceInfo.getCountry()));
        ruleIn.setDeviceCity(RuleUtils.getRuleAppValue(appDeviceInfo.getCity()));
        ruleIn.setDeviceimei(RuleUtils.getRuleAppValue(appDeviceInfo.getImei()));
        ruleIn.setDeviceId(RuleUtils.getRuleAppValue(appDeviceInfo.getFingerprint()));
        ruleIn.setDeviceRoot(RuleUtils.getRuleAppValue(appDeviceInfo.getHasRoot()));
        ruleIn.setContinent(RuleUtils.getRuleAppValue(appDeviceInfo.getCountryState()));
        ruleIn.setPbrand(RuleUtils.getRuleAppValue(appDeviceInfo.getPhoneBrand()).toLowerCase(Locale.ROOT));
        ruleIn.setPtype(RuleUtils.getRuleAppValue(appDeviceInfo.getPhoneModel()).toLowerCase(Locale.ROOT));
        ruleIn.setOpentime(RuleUtils.getRuleAppValue(appDeviceInfo.getStartupTime()));
        ruleIn.setInchargetime(RuleUtils.getRuleAppValue(appDeviceInfo.getChargeCount()));
        ruleIn.setBattery(RuleUtils.getRuleAppValue(appDeviceInfo.getQuantityOfElectricity()));
        ruleIn.setTuoluoyi(RuleUtils.getRuleAppValue(appDeviceInfo.getGyroscopeParameters()));
        ruleIn.setMaxstorage(RuleUtils.getRuleAppValue(appDeviceInfo.getMaxMemory()));
        ruleIn.setUsedstorage(RuleUtils.getRuleAppValue(appDeviceInfo.getUseMemory()));
        ruleIn.setOperator(RuleUtils.getRuleAppValue(appDeviceInfo.getPhoneOperators()));
        ruleIn.setSim(RuleUtils.getRuleAppValue(appDeviceInfo.getHasSimCard()));
        ruleIn.setLongitude(RuleUtils.getRuleAppValue(appDeviceInfo.getLongitude()));
        ruleIn.setLatitude(RuleUtils.getRuleAppValue(appDeviceInfo.getLatitude()));
        ruleIn.setAddress(RuleUtils.getRuleAppValue(appDeviceInfo.getAddress()));
        ruleIn.setWifiname(RuleUtils.getRuleAppValue(appDeviceInfo.getWifiName()));
        ruleIn.setAndroidno(appDeviceInfo.getSystem());
    }

    /**
     * 为ruleIn填充realName数据
     *
     * @param ruleIn
     * @param realName
     */
    public static void setRuleInByRealName(RuleIn ruleIn, RealNameAuth realName, List<SmsAreaNumberConfig> smsAreaNumberConfigs) {
        Map<String, Integer> ageDetail = DateUtils.getAgeDetailByddmmyyyy(realName.getBirthDate());
        ruleIn.setApplyAge(ageDetail.get("year") + "");
        ruleIn.setUserName(realName.getFirstName() + " " + realName.getMiddleName() + " " + realName.getLastName());
        ruleIn.setBvnNumber(realName.getBvnAccount());
        ruleIn.setBvnMobile(realName.getPhoneNumber());
        ruleIn.setGender(StringUtils.equalsAny(realName.getGender(), "0", "M") ? "M" : "F");
        String[] exqApiArray = realName.getExqApi().split(",");
        ruleIn.setKycapiname(exqApiArray[exqApiArray.length - 1]);
        for (int i = 0; i < smsAreaNumberConfigs.size(); i++) {
            if (realName.getPhoneNumber().startsWith(smsAreaNumberConfigs.get(i).getAreaNumber())) {
                ruleIn.setBvnphoneoperator(smsAreaNumberConfigs.get(i).getSmsMarketingMode());
                break;
            }
        }

    }

    /**
     * 为ruleIn填充appUser数据
     *
     * @param ruleIn
     * @param appUser
     * @param overduePhones
     */
    public static void setRuleInByAppUser(RuleIn ruleIn, AppUser appUser, List<Map<String, String>> overduePhones, List<SmsAreaNumberConfig> smsAreaNumberConfigs) {
        //注册手机号码是否逾期
        ruleIn.setCorrelationUserOverdueFlag(overduePhones.contains(appUser.getPhone()) ? "1" : "0");
        ruleIn.setMobile(appUser.getPhone());

        for (int i = 0; i < smsAreaNumberConfigs.size(); i++) {
            if (appUser.getPhone().startsWith(smsAreaNumberConfigs.get(i).getAreaNumber())) {
                ruleIn.setRegphoneoperator(smsAreaNumberConfigs.get(i).getSmsMarketingMode());
                break;
            }
        }
    }

    public static String monthlyIncomeFormat(String monthlyIncome) {
        double i = 0;
        try {
            i = Double.parseDouble(monthlyIncome);
        } catch (Exception e) {
            log.error("月收入monthlyIncome = {}, 为 App2.0 枚举", monthlyIncome);
            return monthlyIncome;
        }
        //枚举1-6 小于10说明是旧版app用户
        if (i > 10) {
            if (i < 30000) {
                return "1";
            }
            if (i < 50000) {
                return "2";
            }
            if (i < 100000) {
                return "3";
            }
            if (i < 200000) {
                return "4";
            }
            if (i < 500000) {
                return "5";
            }
            if (i >= 500000) {
                return "6";
            }
        }
        return monthlyIncome;
    }

}
